package make.free.app.mcaro.Dialog;

import make.free.app.mcaro.R;
import make.free.app.mcaro.activity.Game;
import make.free.app.mcaro.bluetooth.BluetoothChatService;
import make.free.app.mcaro.game.Chat;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Dialog_Chat extends Dialog implements
		android.view.View.OnClickListener {

	private Context mContext;
	private Button btnSend, btnCancel;
	private EditText edt;
	private BluetoothChatService mChatService;
	public ListView lv;

	public Dialog_Chat(Context context, BluetoothChatService mChatServices) {
		super(context);
		// TODO Auto-generated constructor stub
		mContext = context;
		this.mChatService = mChatServices;
		iniDialog();
	}

	/**
	 * init view dialog
	 */
	public void iniDialog() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setCancelable(false);
		setContentView(R.layout.dialog_chat);
		lv = (ListView) findViewById(R.id.listView_chat);
		btnSend = (Button) findViewById(R.id.dialog_btn_send);
		btnCancel = (Button) findViewById(R.id.dialog_btn_cancel);
		edt = (EditText) findViewById(R.id.dialog_ed_chat);

		lv.setAdapter(Game.mConversationArrayAdapter);
		btnSend.setOnClickListener(this);
		btnCancel.setOnClickListener(this);

	}

	@SuppressWarnings("unused")
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.dialog_btn_send) {
			String text = edt.getText().toString();
			Log.e("SIZE TEXT",""+text.length());
			
			if (!text.equalsIgnoreCase("")) {
				Game.mConversationArrayAdapter.add("Tôi:  " + text);
				Game.mConversationArrayAdapter.notifyDataSetChanged();
				if (!Game.isGameAI) {
					String message = "0-" + text;
					sendMessage(message);
				}
				edt.setText("");
			} else {
				Toast.makeText(mContext, "Bạn chưa gõ nội dung",
						Toast.LENGTH_SHORT).show();
			}

		}
		if (v.getId() == R.id.dialog_btn_cancel) {
			if (!Game.isGameAI)
				Dialog_Choice_Player.mChat
						.setBackgroundResource(R.drawable.chat_offline);
			Chat.onchageICONOffline();
			dismiss();
		}
	}

	private void sendMessage(String message) {
		// Check that we're actually connected before trying anything
		if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
			Toast.makeText(mContext, R.string.not_connected, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		if (message.length() > 0) {
			// Get the message bytes and tell the BluetoothChatService to write
			byte[] send = message.getBytes();
			mChatService.write(send);

		}
	}

}
